<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j list search-list page-list">
    <div class="content">
      <div
        v-if="categoryId"
        class="crumbs"
      >
        <router-link
          to="/"
          class="item-a"
        >
          {{ $t('commonHead.home') }}
        </router-link>
        <span
          v-if="categoryId"
          class="arrow"
        > > </span>
        <template
          v-for="(cate, index) in parentCategoryList"
          :key="index"
        >
          <span
            v-if="categoryParentId === cate.categoryId"
            class="item-a"
            @click="changeCategory(0, cate.categoryId)"
          >{{ cate.categoryName }}</span>
        </template>
        <template
          v-for="(cate, index) in categoryList"
          :key="index"
        >
          <span
            v-if="categoryId === cate.categoryId"
            class="item-span"
          >
            <span class="arrow"> > </span>
            {{ cate.categoryName }}
          </span>
        </template>
        <span
          v-if="keyword"
          class="arrow"
        > > </span>
        <span
          v-if="keyword"
          class="item-span center"
        >{{ keyword }}</span>
      </div>
      <div
        v-else
        class="crumbs"
      >
        <router-link
          to="/"
          class="item-a"
        >
          {{ $t('commonHead.home') }}
        </router-link>
        <span class="arrow">></span>
        <span
          v-if="keyword"
          class="item-span center"
        >{{ keyword }}</span>
        <span
          v-if="st === 0"
          class="item-span"
        >{{ $t('commonHead.productList') }}</span>
        <span
          v-if="st === 1"
          class="item-span"
        >{{ $t('commonHead.newProducts') }}</span>
        <span
          v-if="st === 4"
          class="item-span"
        >{{ $t('commonHead.couponPooling') }}</span>
      </div>
      <div
        v-if="!st"
        class="goods-sort"
      >
        <div class="sort-con categorys">
          <div class="name">
            {{ $t('classification') }}：
          </div>
          <div class="group">
            <span
              class="item"
              :class="[{ active: !categoryParentId }]"
              @click="changeCategory(-1, 0)"
            >{{ $t('all') }}</span>
            <span
              v-for="cate in parentCategoryList"
              :key="cate.categoryId"
              :class="[
                'item',
                categoryParentId === cate.categoryId ? 'active' : ''
              ]"
              @click="changeCategory(0, cate.categoryId)"
            >{{ cate.categoryName }}</span>
          </div>
        </div>
        <div
          v-show="categoryList.length && categoryParentId"
          class="sort-con categorys"
        >
          <div class="name">
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          </div>
          <div class="group">
            <span
              v-for="subCate in categoryList"
              :key="subCate.categoryId"
              :class="[
                'item',
                categoryId === subCate.categoryId ? 'active' : ''
              ]"
              @click="changeCategory(1, subCate.categoryId)"
            >{{ subCate.categoryName }}</span>
          </div>
        </div>
        <div
          v-show="thCategoryList.length && categoryId"
          class="sort-con categorys"
        >
          <div class="name">
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          </div>
          <div class="group">
            <span
              v-for="threeCate in thCategoryList"
              :key="threeCate.categoryId"
              :class="[
                'item',
                thCategoryId === threeCate.categoryId ? 'active' : ''
              ]"
              @click="changeCategory(2, threeCate.categoryId)"
            >{{ threeCate.categoryName }}</span>
          </div>
        </div>

        <div class="sort-con sorts">
          <div class="name">
            {{ $t('sort') }}：
          </div>
          <div class="group">
            <span
              :class="['item', sortType === '' ? 'active' : '']"
              @click="onStsTap('')"
            >{{ $t('default') }}</span>
            <span
              :class="['item', sortType === 'sales' ? 'active' : '']"
              @click="onStsTap('sales')"
            >
              {{ $t('sales') }}
              <i
                v-if="sort === 3 && sortType === 'sales'"
                class="arrow-up"
              />
              <i
                v-if="sort === 2 && sortType === 'sales'"
                class="arrow-down"
              />
            </span>
            <span
              :class="['item', sortType === 'price' ? 'active' : '']"
              @click="onStsTap('price')"
            >
              {{ $t('price') }}
              <i
                v-if="sort === 5 && sortType === 'price'"
                class="arrow-up"
              />
              <i
                v-if="sort === 4 && sortType === 'price'"
                class="arrow-down"
              />
            </span>
          </div>
        </div>
      </div>
      <div
        class="goods-list"
      >
        <!-- 全部 -->
        <prod-item
          :is-loaded="isLoaded"
          :pale-list="dataList"
          :list-type="1"
          :page-type="1"
          @update-pic-indext="updatePicIndext"
          @hand-click="goListIndex"
        />
        <!-- 页码 -->
        <pagination
          v-model="current"
          :pages="pages"
          @change-page="changePage()"
        />
        <!-- /页码 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { useCategoryHorizontalStore } from '@/stores/category-horizontal.js'

const route = useRoute()
const router = useRouter()

const categoryHorizontalStore = useCategoryHorizontalStore()
const parentCategoryList = computed(() => {
  return categoryHorizontalStore.parentCategoryList
})

const categoryList = computed(() => {
  return categoryHorizontalStore.categoryList
})

const thCategoryList = computed(() => {
  return categoryHorizontalStore.thCategoryList
})

const thCategoryId = ref('')
const st = ref(Number(route.query.st) || 0)
const dataList = ref([])
const keyword = ref('') // 搜索关键字

onMounted(() => {
  if (st.value === 1) {
    document.title = $t('commonHead.newProducts')
  } else {
    document.title = $t('commonHead.productList')
  }
  if (route.query.sort) {
    sort.value = route.query.sort / 1
  }
  keyword.value = route.query.pn || ''
  getDataList(route.query)
  if (!thCategoryId.value) {
    categoryHorizontalStore.initThCategoryList([])
    getCategory(0)
    getCategory(1)
  } else {
    getCategory(0)
    getCategory(1)
    getCategory(2)
  }
})

/** 获取数据列表
 * st: 搜索方式 空为默认 1新品推荐 2
 * pn: 商品名称
 * cpid: 上级分类id
 * cid: 分类id
 * sort: 根据默认(0)/销量(1)/价格(2)排序
 * ob: 0正序 1倒序
 * c: 当前第几页
 */
const isLoaded = ref(false)
const pages = ref(1) // 总页数
const current = ref(1) // 当前页数
const getDataList = (queryPar = {}) => {
  const query = queryPar
  sortType.value = (!query.sort || query.sort === 0) ? '' : (query.sort === 4 || query.sort === 5) ? 'price' : 'sales'
  let param = {
    st: Number(query.st) || 0,
    current: Number(query.c) || 1,
    size: 12 // 每页显示多少条
  }
  let url
  if (param.st === 1) {
    url = '/search/page'
    param = Object.assign({
      keyword: query.pn || '',
      categoryId: Number(query.thCid) || '',
      sort: 21, // 这里的sort并不是排序 是 状态
      orderBy: Number(query.ob) || 0, // 这里的orderby 才是状态
      current: Number(query.c) || 1, // 这里是页码
      isAllProdType: true,
      isActive: 1 // 过滤掉活动商品
    }, param)
    categoryParentId.value = Number(query.cpid) || ''
    categoryId.value = Number(query.cid) || ''
    thCategoryId.value = Number(query.thCid) || ''
  } else if (param.st === 4 && query.couponId) {
    url = '/coupon/prodListByCouponId'
    param = Object.assign({
      couponId: query.couponId,
      prodName: query.pn || '',
      categoryId: Number(query.thCid) || '',
      sort: Number(query.sort) || 0, // 这里的sort并不是排序 是 状态
      orderBy: Number(query.ob) || 0, // 这里的orderby 才是状态
      current: Number(query.c) || 1, // 这里是页码
      isAllProdType: true
    }, param)
    categoryParentId.value = Number(query.cpid) || ''
    categoryId.value = Number(query.cid) || ''
    thCategoryId.value = Number(query.thCid) || ''
  } else if (query.cpid && !query.cid && !query.thCid) {
    url = '/search/page'
    param = Object.assign({
      keyword: query.pn || '',
      categoryId: Number(query.thCid) || '',
      primaryCategoryId: query.cpid,
      sort: Number(query.sort) || null, // 这里的sort并不是排序 是 状态
      orderBy: Number(query.ob) || 0, // 这里的orderby 才是状态
      current: Number(query.c) || 1, // 这里是页码
      isAllProdType: true,
      isActive: 1 // 过滤掉活动商品
    }, param)
    categoryParentId.value = Number(query.cpid) || ''
  } else if (query.cpid && query.cid && !query.thCid) {
    url = '/search/page'
    param = Object.assign({
      keyword: query.pn || '',
      categoryId: Number(query.thCid) || '',
      secondaryCategoryId: query.cid,
      sort: Number(query.sort) || null, // 这里的sort并不是排序 是 状态
      orderBy: Number(query.ob) || 0, // 这里的orderby 才是状态
      current: Number(query.c) || 1, // 这里是页码
      isAllProdType: true,
      isActive: 1 // 过滤掉活动商品
    }, param)
    categoryParentId.value = Number(query.cpid) || ''
    categoryId.value = Number(query.cid) || ''
  } else {
    url = '/search/page'
    param = Object.assign({
      keyword: query.pn || '',
      categoryId: Number(query.thCid) || '',
      sort: Number(query.sort) || null, // 这里的sort并不是排序 是 状态
      orderBy: Number(query.ob) || 0, // 这里的orderby 才是状态
      current: Number(query.c) || 1, // 这里是页码
      isAllProdType: true,
      isActive: 1 // 过滤掉活动商品
    }, param)
    categoryParentId.value = Number(query.cpid) || ''
    categoryId.value = Number(query.cid) || ''
    thCategoryId.value = Number(query.thCid) || ''
  }
  http.get(url, {
    params: param
  }).then(({ data }) => {
    pages.value = data.pages
    dataList.value = data.records[0].products.map(item => Object.assign(item, { imgs: item.imgs ? item.imgs.split(',') : null, currentActive: 0 }))
    isLoaded.value = !dataList.value.length
  })
}

const categoryParentId = ref(null)
watch(() => categoryParentId.value, () => {
  getCategory(1)
})

const categoryId = ref('')
watch(() => categoryId.value, () => {
  getCategory(2)
})

watch(() => route.query, () => {
  if (Number(route.query.st) === 1) {
    document.title = $t('commonHead.newProducts')
  }
  if (Number(route.query.st) === 0) {
    document.title = $t('commonHead.productList')
  }
}, { deep: true })

/**
 * 获取分类
 * @param level 0 一级分类 1 二级分类
 */
const getCategory = (level) => {
  let categoryParentIdPar = 0
  if (level === 1) {
    if (!categoryParentId.value || categoryParentId.value === '0') {
      categoryHorizontalStore.initCategoryList(parentCategoryList.value)
    } else {
      categoryParentIdPar = categoryParentId.value
      http.get('/category/categoryInfo?parentId=' + categoryParentIdPar)
        .then(({ data }) => {
          categoryHorizontalStore.initCategoryList(data.categoryInfo)
        })
    }
  } else if (level === 2) {
    if (!categoryId.value || categoryId.value === '0') {
      categoryHorizontalStore.initParentCategoryList(parentCategoryList.value)
    } else {
      categoryParentIdPar = categoryId.value
      http.get('/category/categoryInfo?parentId=' + categoryParentIdPar)
        .then(({ data }) => {
          categoryHorizontalStore.initThCategoryList(data.categoryInfo)
        })
    }
  } else {
    categoryHorizontalStore.initParentCategoryList(parentCategoryList.value)
  }
}

/**
 * 改变分类
 * @param level 0 一级分类 1 二级分类 2三级分类
 * @param categoryIdPar 分类id
 */
const changeCategory = (level, categoryIdPar) => {
  if (level === -1) {
    categoryParentId.value = ''
    categoryId.value = ''
    categoryHorizontalStore.reomveCategoryList()
  } else if (level === 0) {
    if (categoryParentId.value === categoryIdPar) {
      getCategory(1)
    }
    categoryParentId.value = categoryIdPar
    categoryHorizontalStore.reomveThCategoryList()
  } else if (level === 1) {
    if (categoryId.value === categoryIdPar) {
      getCategory(2)
    }
    categoryId.value = categoryIdPar
  } else if (level === 2) {
    thCategoryId.value = categoryIdPar
  }
  if (level === -1) {
    getSearchProdPage()
  }
  if (level === 0) {
    getSearchProdPage(1)
  }
  if (level === 1) {
    getSearchProdPage(1, 2)
  }
  if (level === 2) {
    getSearchProdPage(1, 2, 3)
  }
}

// 切换页数
const changePage = () => {
  if (categoryParentId.value && categoryId.value && thCategoryId.value) {
    getSearchProdPage(current.value, 2, 3)
  } else if (categoryParentId.value && categoryId.value) {
    getSearchProdPage(current.value, 2)
  } else {
    getSearchProdPage(current.value)
  }
}

const couponId = null // 优惠券id
const sort = ref(0)
/**
 * 请求商品列表
 */
const getSearchProdPage = (currentPar, cid, thcid) => {
  let query
  if (currentPar === undefined) {
    query = {
      st: st.value,
      pn: keyword.value || ''
    }
  } else {
    query = {
      st: st.value,
      couponId: couponId || '',
      cpid: categoryParentId.value || '',
      c: currentPar,
      pn: keyword.value || '',
      cid: cid ? categoryId.value : '',
      thCid: (cid && thcid) ? thCategoryId.value : '',
      sort: sort.value || 0,
      ob: 0
    }
  }
  getDataList(query)
}

const sortType = ref('')
/**
 * 切换排序
 * @param {Number/String} sortTypePar 排序类型
 */
const onStsTap = (sortTypePar) => {
  sortType.value = sortTypePar
  if (!sortType.value) {
    sort.value = 0
  } else if (sortType.value === 'sales') {
    sort.value = sort.value === 3 ? 2 : 3
  } else if (sortType.value === 'price') {
    sort.value = sort.value === 5 ? 4 : 5
  }
  current.value = 1
  if (categoryParentId.value && categoryId.value && thCategoryId.value) {
    getSearchProdPage(1, 2, 3)
  } else if (categoryParentId.value && categoryId.value) {
    getSearchProdPage(1, 2)
  } else if (categoryParentId.value) {
    getSearchProdPage(1)
  } else {
    getSearchProdPage(current.value)
  }
}

/**
 * 用于更新子组件中列表每个商品当前图片索引，比较抽象
 */
const updatePicIndext = (index, newValue) => {
  dataList.value[index].currentActive = newValue
}

const goListIndex = () => {
  router.push({
    path: '/index',
    query: {
      st: 0
    }
  })
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
